package com.zhhe.algorithm;

public class SearchAlgorithm {

    /**
     * 二分查找
     */
    public static int binarySearch(int[] arr, int key) {
        if (arr == null) {
            return -1;
        }
        int low = 0 , high = arr.length - 1, mid = 0;
        while (low <= high) {
            mid = (low + high)/2;
            if (key < arr[mid]) {
                high = mid - 1;
            } else if (key > arr[mid]) {
                low = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] a = null;
        int[] b = {1};
        int[] c = {1,2};
        int[] d = {1,2,3};
        int[] e = {1,2,3,4};
        int[] f = {-1,0,3,5,9,12};

//        int a1 = binarySearch(a, 1);
//        System.out.print("a1 = " +a1);
//        System.out.println();
//        int b1 = binarySearch(b, 1);
//        int b2 = binarySearch(b, 2);
//        System.out.print("b1 = " + b1 + "  b2 = " + b2);
//        System.out.println();
//
//        int c1 = binarySearch(c, 1);
//        int c2 = binarySearch(c, 2);
//        int c3 = binarySearch(c, 3);
//        System.out.print("c1 = " + c1 + "  c2 = " + c2 + "  c3 = " + c3);
//        System.out.println();
//
//        int d1 = binarySearch(d, 1);
//        int d2 = binarySearch(d, 2);
//        int d3 = binarySearch(d, 3);
//        int d4 = binarySearch(d, 4);
//        System.out.print("d1 = " + d1 + "  d2 = " + d2 + "  d3 = " + d3 + "  d4 = " + d4);
//        System.out.println();
//
//        int e1 = binarySearch(e, 1);
//        int e2 = binarySearch(e, 2);
//        int e3 = binarySearch(e, 3);
//        int e4 = binarySearch(e, 4);
//        int e5 = binarySearch(e, 5);
//        System.out.print("e1 = " + e1 + "  e2 = " + e2 + "  e3 = " + e3 + "  e4 = " + e4 + "  e5 = " + e5);

        int f1 = binarySearch(f, 9);
        System.out.println( " f1="+f);
    }
}
